/**
 * 
 */
package com.onewingu.gcs.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.security.GeneralSecurityException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.client.http.AuthSubUtil;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

/**
 * @author er66
 *
 */
@SuppressWarnings("serial")
public class ContactShare extends HttpServlet {
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		//DocsService client = new DocsService("google-feedfetcher-v1");
		ContactsService client = new ContactsService("google-feedfetcher-v1");

		String sessionToken = null;
		TokenStore ts = new TokenStore();

		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");

		UserService userService = UserServiceFactory.getUserService();
		PrintWriter writer = resp.getWriter();

		writer.print("<html><head>");
		writer.print("<script type=\"text/javascript\" src=\"gcontactsync.nocache.js\"></script>");
		writer.print("</head><body><p>");

		// If a user is currently signed in to the application, attempt to retrieve
		// a previously stored session token associated with that account from App
		// Engine's datastore.
		if (userService.isUserLoggedIn()) {
			User user = userService.getCurrentUser();
			sessionToken = ts.getToken(user.getEmail().substring(0, user.getEmail().indexOf('@')));
			writer.print("<br />logged in as " + user.getEmail());
			writer.print("<br />domain: " + user.getAuthDomain());
			writer.print("<br /> Administrator?: " + userService.isUserAdmin());
		} else {
			writer.print("Need to log in");
			String next = req.getRequestURL().toString();
			String loginURL = userService.createLoginURL(next);
			writer.print("<br /><a href=\"" + loginURL + "\">Login</a>");
			writer.print("</p></body></html>");
			return;
		}

		if (sessionToken == null) {
			writer.print("<br />token not found in datastore");

			try {
				String authToken = AuthSubUtil.getTokenFromReply(req.getQueryString());
				authToken = URLDecoder.decode(authToken, "UTF-8");
				writer.print("<br />authToken = " + (authToken == null ? "null" : authToken));
				sessionToken = AuthSubUtil.exchangeForSessionToken(authToken, null);
				writer.print("<br />sessionToken= " + (sessionToken == null ? "null" : sessionToken));
			} catch (AuthenticationException e) {
				writer.print("<br />Authentication Exception " + e);
			} catch (GeneralSecurityException e) {
				writer.print("<br />General Security Exception:<br />" + e);
			} catch (NullPointerException e) {
				// Ignore
			}
		}

		if (sessionToken != null) {

			// If there is a current user, store the token in the datastore and
			// associate it with the current user's unique ID.
			User user = userService.getCurrentUser();
			ts.addToken(user.getEmail().substring(0, user.getEmail().indexOf('@')), sessionToken, "");

			writer.print("<br />Authorized!");

			//client.setAuthSubToken(sessionToken);
			try {
				int numContacts = getContactCount(client);
				writer.print("<br />num contacts: " + numContacts);
			} catch(ServiceException se) {
				writer.print("<br />ServiceException " + se);
			}

			writer.print("<div id=\"groups\"></div>");
			writer.print("</p></body></html>");

		} else {
			// Write AuthSub URL to response
			writer.print("<br />Not authorized");
			String next = req.getRequestURL().toString();
			String scope = "https://www.google.com/m8/feeds/";
			boolean secure = false;
			boolean session = true;
			String authURL = AuthSubUtil.getRequestUrl(next, scope, secure, session);
			writer.print("<br /><a href=\"" + authURL + "\">Authorize</a>");
			writer.print("</p></body></html>");
		}

	}

	public static int getContactCount(ContactsService myService)
	throws ServiceException, IOException {
		// Request the feed
		/*URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
		ContactFeed resultFeed = myService.getFeed(feedUrl, ContactFeed.class);

		return resultFeed.getEntries().size();*/
		return 3;
	}

}
